//
//  AIDiaryReplayBean.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/3/11.
//
/**
 * 评论
 */
import Foundation
import SwiftUI
class AIImageRequstBean : Identifiable ,Encodable {
    
    var stream = false
    var max_tokens: Int64 = configManager.getConfig().AiConfig.maxTokens ?? 1024
    var temperature: Float64 = configManager.getConfig().AiConfig.temperature ?? 0.9
    var top_p: Float64 = configManager.getConfig().AiConfig.top_p ?? 0.95
    var messages: [MessageProtocol]
    var model :String
    
    
    init(model: String?, content: String, url: String) {
        self.model = model ?? ""
        self.messages = AIImageRequstBean.getMessagesList(content: content, url: url)
    }
    
    private static func getMessagesList(content: String, url: String) ->[MessageProtocol] {
        
        let ruleDesc = configManager.getConfig().getAiDescribe().imageDescribe
        
        var listMsg : [MessageProtocol] = []
        
        //先添加AI人设
        listMsg.append(MessagesV2("system", "图像大师", "你是一个图像理解大师"))
        
        var listContentV2 : [MessageContentV2] = []
        if (content).isEmpty == false {
            listContentV2.append(MessageContentV2(0, "日记内容：\(content)", nil))
        }
        listContentV2.append(MessageContentV2(0, ruleDesc, nil))
        listContentV2.append(MessageContentV2(1, nil, url))
        
        listMsg.append(MessagesV3("user", "用户", listContentV2))
        
        return listMsg
    }
    private enum CodingKeys: String, CodingKey {
         case stream, max_tokens, temperature, top_p, messages, model
     }
    
    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(stream, forKey: .stream)
        try container.encode(max_tokens, forKey: .max_tokens)
        try container.encode(temperature, forKey: .temperature)
        try container.encode(top_p, forKey: .top_p)
        try container.encode(model, forKey: .model)
        
        var messagesContainer = container.nestedUnkeyedContainer(forKey: .messages)
        for message in messages {
            if let v2 = message as? MessagesV2 {
                try messagesContainer.encode(v2)
            } else if let v3 = message as? MessagesV3 {
                try messagesContainer.encode(v3)
            }
        }
    }
}
